package com.smt.modules.app.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.smt.common.base.BaseController;
import com.smt.common.enums.Code;
import com.smt.common.utils.*;
import com.smt.modules.bus.entity.EmailStreamEntity;
import com.smt.modules.bus.service.EmailStreamService;
import com.smt.modules.bus.vo.EmailStreamVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Map;


/**
 * 
 *
 */
@RestController
@RequestMapping("app/emailstream")
@Api(tags = {"AppEmailStreamController"},description = "邮箱发送接口")
public class AppEmailStreamController extends BaseController{
    @Autowired
    private EmailStreamService emailStreamService;

    @Autowired
    private EmailUtil emailUtil;
    /**
     * 可以发送多个邮箱用,号分隔
     *
     * @param email
     * @return
     */
    @PostMapping("/send")
    @ApiOperation(value = "可以发送多个邮箱用,号分隔",httpMethod = "POST")
    public R sendEmail(String email){
        //生成验证码
        String code = StringUtil.getFourRandom();
        boolean b = CheckUtil.checkEmail(email);
        if(b){
            EmailStreamEntity emailStreamEntity = new EmailStreamEntity(email,null,1,DateTime.now().toDate(),code);
            emailUtil.sendSimpleMail(email,"易树智造","发送给您的验证码："+code);
            //存数据库
            int count = emailStreamService.selectCount(new EntityWrapper<EmailStreamEntity>()
                    .eq("emails", email)
                    .between("create_time", TimeUtil.getCurrentBeginDate(), TimeUtil.getCurrentEndDate()));
            if(count >=10){
                emailStreamEntity.setIsSuccess(0);
                emailStreamService.insert(emailStreamEntity);
                return R.error(EnumToKeyUtil.toInt(Code.UNKNOWN_ERROR),"您今天发送的次数超出");
            }

            emailStreamEntity.setIsSuccess(1);
            boolean insert = emailStreamService.insert(emailStreamEntity);
            return insert?R.ok("邮箱发送成功"):R.error(EnumToKeyUtil.toInt(Code.SYSTEM_EXCEPTION),"邮箱发送失败");
        }else{
            return R.error(EnumToKeyUtil.toInt(Code.REQUEST_PARAM_ERROR),"邮箱格式验证失败");
        }
    }
}
